package com.travel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.travel.common.CommonRes.RestResponse;
import com.travel.common.util.MD5Util;
import com.travel.feign.LoginFeign;
import com.travel.mapper.UserMapper;
import com.travel.pojo.User;
import com.travel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;

/**
 * @author 18757
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2023-05-09 16:11:18
 */
@Service

public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Resource
    private UserMapper userMapper;

    @Autowired
    private LoginFeign loginFeign;

    private static Jedis jedis = new Jedis("121.40.188.63");

    @Override
    public User checkLogin(String phoneNumber, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenumber", phoneNumber).eq("password", password);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean checkPhone(String phoneNumber) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenumber", phoneNumber);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            return false;//用户查询不到，为空时返回false否则返回true
        } else {
            return true;
        }
    }

    @Override
    public User regist(String phoneNumber, String captcha) {
        User user = new User();
        user.setUsername("xiecheng_" + phoneNumber.substring(7));
        user.setPhonenumber(phoneNumber);

        String pass = MD5Util.getMd5("123");
        user.setPassword(pass);
        userMapper.insert(user);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phonenumber", phoneNumber);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public String getCaptcha(String phoneNumber) {
        //从feign调用接口返回数据中取验证key
        String verificationKey = loginFeign.getGenerateVerificationInfo("sms", phoneNumber, 300);
        int index = verificationKey.indexOf("sms:");
        int end = verificationKey.indexOf("\",\"content\"");
        String key = verificationKey.substring(index, end);

        //验证key存redis
        jedis.set(phoneNumber, key);
        jedis.expire(phoneNumber, 300);
        return key;
    }

    @Override
    public boolean verify(String phoneNumber, String captcha) {
        String verificationKey = jedis.get(phoneNumber);
        RestResponse<Boolean> result = loginFeign.getVerify("sms", verificationKey, captcha);
        return result.getResult().equals(true);
    }
}